﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Asn1.X509;
using Sicurezza.CA.DataProvider;
using Sicurezza.Entita;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Configuration;
using Org.BouncyCastle.OpenSsl;
using System.IO;
using System.Reflection;
using System.Web;

namespace Sicurezza.CA.Manager
{
    public class CrlManager
    {
        private static RevokeDataProvider dataProvider = new RevokeDataProvider();
        private static CrlDataProvider crlDataProvider = new CrlDataProvider();

        private static string PublishPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath,
                ConfigurationManager.AppSettings["CrlPath"]);

        public static void Create()
        {
            X509V2CrlGenerator g = new X509V2CrlGenerator();
            List<RevokedCertificate> revoked = dataProvider.GetAll();
            for (int i = 0; i < revoked.Count; i++)
            {
                g.AddCrlEntry(new BigInteger(revoked[i].CertificateSerial.ToString(), 10), revoked[i].Timestamp, CrlReason.Unspecified);
            }

            g.SetThisUpdate(DateTime.Now);
            g.SetNextUpdate(DateTime.Now.AddMonths(1));

            g.SetSignatureAlgorithm("SHA1withRSA");

            X509Name issuer = new X509Name("C=IT, O=Università degli studi di Padova, OU=Scienze MM FF NN, CN=CA");

            g.SetIssuerDN(issuer);
            
            int CrlId = crlDataProvider.Save();

            g.AddExtension(X509Extensions.CrlNumber,
                  false, new CrlNumber(new BigInteger(CrlId.ToString())));

            RsaKeyParameters key = new RsaKeyParameters(true, 
                new BigInteger(KeyManager.GetRSAModulus()), 
                new BigInteger(KeyManager.GetRSAPrivateExponent()));

            
            X509Crl crl = g.Generate(key);

            if (File.Exists(PublishPath))
                File.Delete(PublishPath);

            using (StreamWriter sw = File.CreateText(PublishPath))
            {
                PemWriter pw = new PemWriter(sw);

                pw.WriteObject(crl);

            }
            
            
        }


    }
}
